package com.myapp.myhome.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.SaveCallback;
import com.myapp.myhome.HumanBean;
import com.myapp.myhome.R;
import com.myapp.myhome.adapter.MyGridAdapter;
import com.myapp.myhome.utils.AllUtils;
import com.myapp.myhome.utils.MainUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class SubmitInfoActivity extends BaseActivity {

	private TextView title_text;
	private Button title_btn_back;
	private Spinner spinner_whopay;
	private Button btn_add_note;
	private TextView text_date;
	private EditText edit_money;
	private Button btn_sure;
	private GridView mGridView;
	private PopupWindow popupWindow;
	private View popView;
	private View parent;
	private Button btn_pop_cancle;
	private Button btn_pop_sure;
	private EditText edit_pop_note;

	ArrayList<HumanBean> list = new ArrayList<HumanBean>();
	MyGridAdapter adapter;
	MainUtils mUtils;
	String str;
	String str_who_pay;
	double money;
	String[] languages;
	ArrayList<String> list_names = new ArrayList<String>();
	ArrayList<Bitmap> list_imgs = new ArrayList<Bitmap>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_submitinfo);
		mUtils = new MainUtils(this);
		str = mUtils.getDate();
		parent = findViewById(R.id.submit_main);
		initPopupWindows();
		init();
	}

	private void init() {
		title_text = (TextView) this.findViewById(R.id.titlebar_title);
		title_text.setText("记账");
		title_btn_back = (Button) this.findViewById(R.id.titlebar_back);
		title_btn_back.setVisibility(View.VISIBLE);
		title_btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		// 这边是操作日期显示的textView控件和金额输入控件
		text_date = (TextView) this.findViewById(R.id.main_date_text);
		text_date.setText(str);
		text_date.setOnClickListener(new OnClickListener() {// 点击下去后弹出对话框选择时间

					@Override
					public void onClick(View v) {
						showDatePicker();
					}
				});
		edit_money = (EditText) this.findViewById(R.id.main_edit_money);
		// --------------------------------------------
		// 这边是选择谁先预付的钱
		languages = getResources().getStringArray(R.array.whopay);
		str_who_pay = languages[0];
		spinner_whopay = (Spinner) this.findViewById(R.id.main_whopay_spinner);
		spinner_whopay.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				str_who_pay = languages[arg2];
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		// -------------------------------------------
		// 这边是添加备注的按钮
		btn_add_note = (Button) this.findViewById(R.id.main_btn_add_note);
		btn_add_note.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 让他弹出一个对话框，然后提供输入框 这边准备尝试用另一种类似对话框的
				popupWindow.setAnimationStyle(R.style.popWindow_animation);
				// 点击弹出泡泡窗口
				popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
			}
		});

		// ------------------------------------------
		// 这边是gridview控件
		mGridView = (GridView) this.findViewById(R.id.main_gridview);
		adapter = new MyGridAdapter(this);
		// 准备在这边去获取名字和头像
		mGridView.setAdapter(adapter);

		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				HumanBean bean = null;
				ImageView img = (ImageView) view
						.findViewById(R.id.grid_item_img_choice);
				TextView text_name = (TextView) view
						.findViewById(R.id.grid_item_text_name);
				String name = text_name.getText().toString().trim();
				if (!isSame(name)) {// 当不存在时
					bean = new HumanBean();
					bean.setName(name);
					list.add(bean);
				} else {
					bean = getNameBean(name); // 这边再来一个判断，用来取得名字相同的bean
				}

				if (img.getVisibility() == View.GONE) {
					img.setVisibility(View.VISIBLE);
					bean.setChoice(true);
				} else if (img.getVisibility() == View.VISIBLE) {
					img.setVisibility(View.GONE);
					bean.setChoice(false);
				}
			}
		});

		// -------------------------------------------
		// 这边是操作确定按钮
		btn_sure = (Button) this.findViewById(R.id.main_btn_sure);
		btn_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				submitData();
			}
		});

	}

	String str_note = "";

	private void initPopupWindows() {
		popView = getLayoutInflater().inflate(R.layout.popupwindow, null);
		popupWindow = new PopupWindow(popView,
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setOutsideTouchable(true);
		edit_pop_note = (EditText) popView.findViewById(R.id.pop_edit_note);
		btn_pop_cancle = (Button) popView.findViewById(R.id.pop_btn_cancle);
		btn_pop_cancle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popupWindow.dismiss();
			}
		});
		btn_pop_sure = (Button) popView.findViewById(R.id.pop_btn_sure);
		btn_pop_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				str_note = edit_pop_note.getText().toString().trim();
				popupWindow.dismiss();
			}
		});
	}

	// 显示日期选择器
	private void showDatePicker() {

		Calendar d = Calendar.getInstance(Locale.CHINA);
		// 创建一个日历引用d，通过静态方法getInstance() 从指定时区 Locale.CHINA 获得一个日期实例
		Date myDate = new Date();
		// 创建一个Date实例
		d.setTime(myDate);
		// 设置日历的时间，把一个新建Date实例myDate传入
		int year = d.get(Calendar.YEAR);
		int month = d.get(Calendar.MONTH);
		int day = d.get(Calendar.DAY_OF_MONTH);

		DatePickerDialog dialog = new DatePickerDialog(this,
				new OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {

						SimpleDateFormat dateFormat = new SimpleDateFormat(
								"yyyy-MM-dd");
						Date date = new Date(year - 1900, monthOfYear,
								dayOfMonth);
						String str = dateFormat.format(date);
						text_date.setText(str);

					}
				}, year, month, day);
		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "取消",
				new DatePickerDialog.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
		dialog.show();
	}

	// 判断当前传进来的名字在集合里是否存在相同元素
	private boolean isSame(String name) {

		for (int i = 0; i < list.size(); i++) {
			if (name.equals(list.get(i).getName())) {
				return true;// 要是存在相同的话就返回真
			}
		}
		return false;
	}

	// 取得名字相同的bean
	private HumanBean getNameBean(String name) {
		HumanBean mybean = new HumanBean();
		for (int i = 0; i < list.size(); i++) {
			if (name.equals(list.get(i).getName())) {
				mybean = list.get(i);
			}
		}
		return mybean;
	}

	

	// 提交各种东西
	private void submitData() {
		// 获取金额
		String str_money = edit_money.getText().toString().trim();
		try {
			money = Double.parseDouble(str_money);
			// 接下来显示选中的人
			int tmp = 0;
			String str_people = "";
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).isChoice()) {
					tmp++;
					str_people = str_people + list.get(i).getName() + ",";
				}
			}
			if (!str_people.equals("")) {
				str_people = str_people.substring(0, str_people.length() - 1);
			}
			// 这边将其加入到数据库里 使用的是leancloud，因此就是json格式的数据
			// 准备拿到date 格式类似这样:2015-08-25
			String date = text_date.getText().toString();
			// 创建post
			AVObject post = new AVObject("Expenses");
			post.put("date", date);
			post.put("money", money + "");
			post.put("count", tmp);
			post.put("who", str_people);
			post.put("whopay", str_who_pay);
			post.put("avgpay", String.format("%.2f", (money / tmp)));// 平均值
			post.put("note", str_note);
			showSubDialog(post);

		} catch (Exception e) {
			AllUtils.showToast(SubmitInfoActivity.this, "金额不能为空");
		}

	}

	private void showSubDialog(final AVObject post) {
		// -----------------------以下是对话框操作------------------------------------
		// 这边弹出一个对话框提示是否确定添加
		Builder dialog = new Builder(this);
		dialog.setTitle("提交");
		dialog.setMessage("是否提交本次记账");

		dialog.setPositiveButton("是", new AlertDialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				post.saveInBackground(new SaveCallback() {

					@Override
					public void done(AVException arg0) {
						if (arg0 == null) {
							mUtils.showToast("保存成功");
							finish();
						} else {
							mUtils.showToast("保存失败，请重试");
						}
					}
				});
			}
		});
		dialog.setNegativeButton("否", new AlertDialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		dialog.create().show();
	}

}
